package yi.wuhenbot.Utils;

import jakarta.annotation.PostConstruct;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import yi.wuhenbot.Controller.BotController;

import java.io.IOException;

import okhttp3.*;
import yi.wuhenbot.Service.KimiUserService;
import yi.wuhenbot.dao.KimiUserMapper;

/**
 * kimi工具类
 * @author wuhen
 */

public class KimiUtil {
    @Autowired
    private KimiUserService kimiUserService;
    private static final Logger logger = LoggerFactory.getLogger(BotController.class);


    /**
     * kimi api密钥
     */
    @Value("${kimi.apikey}")
    private String KIMI_API_KEY;
    /**
     * kimi模型
     */
    @Value("${kimi.model}")
    private String KIMI_MODEL;

    /**
     * 调用kimi api
     * 参数包括：header的apikey、body的model、messages
     * @return 回复
     */
    public static JSONObject callKimiApi(String user_id, String messages, String content)   {
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        String json = "{\n" +
                "    \"model\": \"moonshot-v1-8k\",\n" +
                "    \"temperature\": 0.6,\n";
        json = json+messages +
                "}";
        System.out.println("json:：：："+json);
        RequestBody body = RequestBody.create(mediaType, json);
        String url = "https://api.moonshot.cn/v1/chat/completions";
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer sk-yAru8CevMYG4c2frt91VnDANXAwpk4XCIsg2RfwVBEYRU5zg")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("异常状态码 code " + response);
            }
            JSONObject responseJson = new JSONObject(response.body().string());

            String string = responseJson.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
            // 更新用户total_tokens
            int totalTokens = responseJson.getJSONObject("usage").getInt("total_tokens");
            //生成返回json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("content",string);
            jsonObject.put("total_tokens",totalTokens);

            // logger.info("对话结果："+string);
            // 返回对话内容
            return jsonObject;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}


